import { initBaseUrl,request } from '../../../utils/request';
export default {
	data() {
		return {
			scrollToLetter: '',
			selectedProvince: {},
			selectedCity: {},
			selectedDistrict: {},
			currentLevel: 1,
			fromPage: 'index',
			regionData: {
				provinces: {},
				cities: {},
				districts: {}
			},
			loading: true,
			provinceList: [],
			cityList: [],
			districtList: []
		}
	},
	onLoad(options) {
		console.log('onLoad触发，参数:', options);
		// 接收来源页面参数，如果没有则使用默认值
		this.fromPage = options.fromPage || 'index';
		console.log('即将调用loadRegionData...');
		 this.loadRegionData();
	},
	onUnload() {
		// 页面卸载时的清理工作
	},
	methods: {
		// 加载区域数据
		async loadRegionData() {
			console.log('开始加载区域数据...');
			this.loading = true;
			try {
				console.log('即将调用getRegionData...');
				const provinces = await this.getRegionData();
				console.log('获取到的省份数据:', provinces);
				this.provinceList = provinces;
				this.groupRegionData(provinces, 'provinces');
				console.log('分组后的省份数据:', this.regionData.provinces);
			} catch (error) {
				console.error('加载区域数据失败:', error);
				// 如果API失败，使用本地模拟数据
				this.loadMockData();
			} finally {
				this.loading = false;
			}
		},

		// 从后端API获取区域数据
		getRegionData(pid = 0) {
			console.log('调用getRegionData，参数pid:', pid);
			return new Promise((resolve, reject) => {
				request({
					url: `/common/getRegionData`,
					method: 'GET',
					data: { pid },
					success: (res) => {
						console.log('getRegionData请求成功，响应:', res);
						if (res.data && res.data.code === 1) {
							resolve(res.data.data);
						} else {
							console.warn('API返回错误:', res.data ? res.data.msg : '未知错误');					// API返回错误时也使用本地数据
							this.loadMockData();
							resolve([]);
						}
					},
					fail: (err) => {
						console.error('getRegionData请求失败:', err);
						// 网络请求失败时使用本地数据
						this.loadMockData();
						resolve([]);
					}
				});
			});
		},

		// 加载城市数据
		async loadCities(provinceId, provinceName) {
			this.loading = true;
			try {
				const cities = await this.getRegionData(provinceId);
				if (cities && cities.length > 0) {
					this.cityList = cities;
					this.groupRegionData(cities, 'cities');
				} else {
					// 如果没有数据，也使用本地模拟数据
					this.loadMockCities(provinceId);
				}
			} catch (error) {
				console.error('加载城市数据失败:', error);
				this.loadMockCities(provinceId);
			} finally {
				this.loading = false;
			}
		},

		// 加载区县数据
		async loadDistricts(cityId, cityName) {
			this.loading = true;
			try {
				const districts = await this.getRegionData(cityId);
				if (districts && districts.length > 0) {
					this.districtList = districts;
					this.groupRegionData(districts, 'districts');
				} else {
					// 如果没有数据，使用空数组
					this.districtList = [];
					this.groupRegionData([], 'districts');
				}
			} catch (error) {
				console.error('加载区县数据失败:', error);
				this.districtList = [];
				this.groupRegionData([], 'districts');
			} finally {
				this.loading = false;
			}
		},

		// 本地模拟城市数据
		loadMockCities(provinceId) {
			const mockCities = [
				{ id: 110100, pid: 110000, name: '北京市', short_name: '北京', level: 2, code: '110100', first: 'B', lng: '116.405285', lat: '39.904989' },
				{ id: 120100, pid: 120000, name: '天津市', short_name: '天津', level: 2, code: '120100', first: 'T', lng: '117.190182', lat: '39.125596' },
				{ id: 130100, pid: 130000, name: '石家庄市', short_name: '石家庄', level: 2, code: '130100', first: 'S', lng: '114.502461', lat: '38.045474' },
				{ id: 440100, pid: 440000, name: '广州市', short_name: '广州', level: 2, code: '440100', first: 'G', lng: '113.280637', lat: '23.125178' },
				{ id: 310100, pid: 310000, name: '上海市', short_name: '上海', level: 2, code: '310100', first: 'S', lng: '121.472644', lat: '31.231706' }
			];
			const filteredCities = mockCities.filter(city => city.pid === provinceId);
			this.cityList = filteredCities;
			this.groupRegionData(filteredCities, 'cities');
		},



		// 分组区域数据
		groupRegionData(data, type) {
			const grouped = {};
			data.forEach(item => {
				const firstLetter = item.first || item.name.charAt(0).toUpperCase();
				if (!grouped[firstLetter]) {
					grouped[firstLetter] = [];
				}
				grouped[firstLetter].push(item);
			});
			this.$set(this.regionData, type, grouped);
		},

		// 选择省份
		async selectProvince(province) {
			this.selectedProvince = province;
			this.selectedCity = {};
			this.selectedDistrict = {};
			this.currentLevel = 2;
			await this.loadCities(province.id, province.name);
			console.log('选择省份:', this.selectedProvince);
		},

		// 选择城市
		async selectCity(city) {
			this.selectedCity = city;
			this.selectedDistrict = {};

			await this.loadDistricts(city.id, city.name);
			const hasDistricts = this.districtList && this.districtList.length > 0;
			
			if (hasDistricts) {
				this.currentLevel = 3;
			} else {
				// 如果没有区县数据，给用户提示后完成选择
				uni.showToast({
					title: '该城市暂无区县数据',
					icon: 'none',
					duration: 2000
				});
				this.selectedDistrict = { id: 0, name: '' }; // 空区县对象
				setTimeout(() => {
					this.completeSelection();
				}, 1000);
				console.log('该城市没有区县数据，直接完成选择');
			}
			console.log('选择城市:', this.selectedCity);
		},

		// 选择区县
		selectDistrict(district) {
			this.selectedDistrict = district;
			this.completeSelection();
			console.log('选择区县:', this.selectedDistrict);
		},

		// 本地模拟数据（备用）
		loadMockData() {
			console.log('使用本地模拟数据');
			const mockProvinces = [
				{ id: 110000, pid: 0, name: '北京市', short_name: '北京', level: 1, code: '110000', first: 'B', lng: '116.405285', lat: '39.904989' },
				{ id: 120000, pid: 0, name: '天津市', short_name: '天津', level: 1, code: '120000', first: 'T', lng: '117.190182', lat: '39.125596' },
				{ id: 130000, pid: 0, name: '河北省', short_name: '河北', level: 1, code: '130000', first: 'H', lng: '114.502461', lat: '38.045474' },
				{ id: 440000, pid: 0, name: '广东省', short_name: '广东', level: 1, code: '440000', first: 'G', lng: '113.280637', lat: '23.125178' },
				{ id: 310000, pid: 0, name: '上海市', short_name: '上海', level: 1, code: '310000', first: 'S', lng: '121.472644', lat: '31.231706' }
			];
			this.provinceList = mockProvinces;
			this.groupRegionData(mockProvinces, 'provinces');
		},

		// 完成选择
		completeSelection() {
			const selectedRegion = {
				province: this.selectedProvince.name || '',
				city: this.selectedCity.name || '',
				district: this.selectedDistrict.name || ''
			};
			
			// 保存到本地存储
			uni.setStorageSync('selectedRegion', selectedRegion);
			
			// 拼接完整地址
			let fullAddress = '';
			if (selectedRegion.province) fullAddress += selectedRegion.province;
			if (selectedRegion.city) fullAddress += selectedRegion.city;
			if (selectedRegion.district) fullAddress += selectedRegion.district;
			
			// 跳转到地图页面，并传递地区信息
			uni.navigateTo({
				url: `/pages/release/map-page?address=${encodeURIComponent(fullAddress)}&fromPage=${encodeURIComponent(this.fromPage)}`
			});
		},

		// 返回上一级
		navigateBack() {
			uni.navigateBack({
				delta: 1
			});
		},

		// 获取当前字母索引
		getCurrentLetters() {
			if (this.currentLevel === 1) {
				return Object.keys(this.regionData.provinces || {});
			} else if (this.currentLevel === 2) {
				return Object.keys(this.regionData.cities || {});
			} else if (this.currentLevel === 3) {
				return Object.keys(this.regionData.districts || {});
			}
			return [];
		},

		// 滚动到指定字母
		scrollToLevelLetter(letter) {
			if (!letter) return;
			
			let targetId = '';
			if (this.currentLevel === 1) {
				targetId = 'province-' + letter;
			} else if (this.currentLevel === 2) {
				targetId = 'city-' + letter;
			} else if (this.currentLevel === 3) {
				targetId = 'district-' + letter;
			}
			
			this.scrollToLetter = targetId;
			
			// 添加延时重置，以便下次点击同一字母也能生效
			setTimeout(() => {
				this.scrollToLetter = '';
			}, 500);
		},

		// 切换选择级别
		switchLevel(level) {
			if (level === 3 && !this.selectedCity.name) return;
			if (level === 2 && !this.selectedProvince.name) return;
			this.currentLevel = level;
			this.scrollToLetter = '';
		}
	}
}